package cn.weibo.batis.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class DateTypeHandler extends BaseTypeHandler<Date> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i,
			Date parameter, JdbcType jdbcType) throws SQLException {
		Timestamp timestamp = new Timestamp(parameter.getTime());
		ps.setTimestamp(i, timestamp);
	}

	@Override
	public Date getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		Timestamp timestamp = rs.getTimestamp(columnName);
		Date date = null;
		if(timestamp != null) {
			date = new Date(timestamp.getTime());
		}
		return date;
	}

	@Override
	public Date getNullableResult(ResultSet rs, int columnIndex)
			throws SQLException {
		Timestamp timestamp = rs.getTimestamp(columnIndex);
		Date date = null;
		if(timestamp != null) {
			date = new Date(timestamp.getTime());
		}
		return date;
	}

	@Override
	public Date getNullableResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		Timestamp timestamp = cs.getTimestamp(columnIndex);
		Date date = null;
		if(timestamp != null) {
			date = new Date(timestamp.getTime());
		}
		return date;
	}
}
